/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.swapper.json;

import com.swapper.json.io.JsonReader;
import com.swapper.json.io.JsonWriter;

import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * JSON document(text).
 * In the JSON RFC4627 standard, there are only JSON array and object.
 *
 * @see JsonArray JSON array implement.
 * @see JsonObject JSON object implement.
 */
public abstract class JsonDocument extends JsonValue {
  /**
   * Static constructor.
   * Construct a JSON document(text) instance from a JSON string.
   *
   * @param json a JSON document(text) string.
   * @return an instance constructed from a JSON string.
   * @see JsonDocument#fromJson(Reader)
   */
  public static JsonDocument fromJson(String json) {
    return fromJson(new StringReader(json));
  }

  /**
   * Static constructor.
   * Construct a JSON document(text) instance from a JSON reader.
   *
   * @param reader a JSON document(text) reader.
   * @return an instance constructed from a JSON reader.
   * @throws NullPointerException if reader is null.
   */
  public static JsonDocument fromJson(Reader reader) {
    return JsonReader.read(reader);
  }

  /**
   * Returns the JSON value as a value of type {@link java.lang.String}.
   *
   * @return the JSON value as a value of type {@link java.lang.String}.
   * @see Object#toString()
   * @see JsonValue#toString()
   */
  @Override
  public final String toString() {
    return toJson();
  }

  /**
   * Convert to a JSON formatted string.
   *
   * @return the JSON formatted string.
   * @see JsonWriter#write(JsonDocument)
   */
  @Override
  public final String toJson() {
    StringWriter writer = new StringWriter();
    JsonWriter.write(writer, this);
    return writer.toString();
  }
}
